<template>
  <div class="notice-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1 class="page-title">公告列表</h1>
    </div>

    <!-- 添加公告区域 -->
    <div class="add-section">
      <div class="form-row">
        <input
          type="text"
          placeholder="请输入标题"
          class="form-input title-input"
          v-model="title"
        />
        <input
          type="text"
          placeholder="请输入内容"
          class="form-input content-input"
          v-model="content"
        />
        <select class="form-input category-select" v-model="selectedCategoryId">
          <option value="">请选择分类</option>
          <option v-for="category in categories" :key="category._id" :value="category._id">
            {{ category.name }}
          </option>
        </select>
        <button class="add-btn" @click="add">
          <span class="btn-icon">+</span>
          添加
        </button>
      </div>
    </div>

    <!-- 公告列表 -->
    <div class="notice-list">
      <div class="list-header">
        <div class="header-item">创建时间</div>
        <div class="header-item">标题</div>
        <div class="header-item">内容</div>
        <div class="header-item">操作</div>
      </div>

      <div v-if="items.length === 0" class="empty-state">
        <div class="empty-icon">📢</div>
        <p>暂无公告数据</p>
      </div>

      <div v-else class="list-content">
        <div v-for="item in items" :key="item._id" class="list-item">
          <div class="item-cell time-cell">
            <span class="create-time">{{ item.createTime }}</span>
          </div>
          <div class="item-cell title-cell">
            <span class="notice-title">{{ item.title }}</span>
          </div>
          <div class="item-cell content-cell">
            <span class="notice-content">{{ item.content }}</span>
          </div>
          <div class="item-cell actions">
            <button class="delete-btn" @click="Sc(item._id)">删除</button>
            &nbsp;&nbsp;
            <button class="delete-btn" @click="Xg(item._id)">修改</button>
          </div>
        </div>
      </div>
    </div>
  </div>
  <div class="modal-overlay" v-show="flag" @click="flag = false">
    <div class="edit-section" @click.stop>
      <input type="text" v-model="mc" placeholder="请输入公告标题" />
      <input type="text" v-model="gm" placeholder="请输入公告内容" />
      <button @click="Bc(id)">保存</button>
      <button @click="flag = false">取消</button>
    </div>
  </div>
</template>

<script>
import axios from 'axios'
export default {
  data() {
    return {
      items: [],
      title: '',
      content: '',
      categories: [],
      selectedCategoryId: '',
      flag: false,
      mc: '',
      gm: '',
      id: null,
    }
  },
  methods: {
    // 获取公告列表
    async fetchNoticeList() {
      try {
        const res = await axios.get('http://47.94.6.186:3001/admin/notice/list', {
          headers: {
            token: localStorage.getItem('loginToken'),
          },
        })
        console.log('公告列表数据:', res.data.data.list)
        this.items = res.data.data.list || []
      } catch (error) {
        console.error('获取公告列表失败:', error)
        this.items = []
        if (error.response?.status === 401) {
          alert('登录已过期，请重新登录')
          this.$router.push('/login')
        }
      }
    },

    // 获取分类列表
    async fetchCategories() {
      try {
        const res = await axios.get('http://47.94.6.186:3001/admin/notice-category/list', {
          headers: {
            token: localStorage.getItem('loginToken'),
          },
        })
        console.log('分类列表数据:', res.data.data.list)
        this.categories = res.data.data.list || []
      } catch (error) {
        console.error('获取分类列表失败:', error)
        this.categories = []
      }
    },

    async add() {
      if (!this.selectedCategoryId) {
        alert('请选择分类')
        return
      }
      await axios
        .post('http://47.94.6.186:3001/admin/notice/create', {
          title: this.title,
          content: this.content,
          categoryId: this.selectedCategoryId,
          token: localStorage.getItem('loginToken'),
        })
        .then((res) => {
          console.log(res.data.data)
          this.items.push(res.data.data)
          this.title = ''
          this.content = ''
          this.selectedCategoryId = ''
        })
    },
    Sc(id) {
      axios
        .delete(`http://47.94.6.186:3001/admin/notice/delete/${id}`, {
          headers: {
            token: localStorage.getItem('loginToken'),
          },
          id: id,
        })
        .then((res) => {
          console.log(res.data.data)
          this.items = this.items.filter((item) => item._id !== id)
        })
    },
    Xg(id) {
      this.flag = true
      this.id = id
      // 获取当前项目的数据填充到编辑框
      this.mc = this.items.find((item) => item._id === id).title
      this.gm = this.items.find((item) => item._id === id).content
    },
    Bc(id) {
      axios
        .put(
          `http://47.94.6.186:3001/admin/notice/update/${id}`,
          {
            title: this.mc,
            content: this.gm,
            categoryId: this.selectedCategoryId,
          },
          {
            headers: {
              token: localStorage.getItem('loginToken'),
            },
          },
        )
        .then((res) => {
          console.log(res.data)
          alert('修改成功')
          this.flag = false
          // 更新本地列表中的数据
          const index = this.items.findIndex((item) => item._id === id)
          if (index !== -1) {
            this.items[index].title = this.mc
            this.items[index].content = this.gm
          }
        })
        .catch((error) => {
          console.error('修改失败:', error)
          alert('修改失败，请重试')
        })
    },
  },
  async mounted() {
    // 获取公告列表和分类列表
    await this.fetchNoticeList()
    await this.fetchCategories()
  },
}
</script>

<style scoped>
.notice-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.page-header {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.page-title {
  font-size: 24px;
  color: #333;
  margin: 0;
  font-weight: 600;
}

.add-section {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.form-row {
  display: flex;
  gap: 15px;
  align-items: center;
}

.form-input {
  padding: 10px 15px;
  border: 2px solid #e1e5e9;
  border-radius: 6px;
  font-size: 14px;
  outline: none;
  transition: border-color 0.3s;
}

.form-input:focus {
  border-color: #2196f3;
}

.title-input {
  width: 200px;
}

.content-input {
  flex: 1;
}

.category-select {
  width: 150px;
  background-color: white;
  cursor: pointer;
}

.add-btn {
  background: linear-gradient(135deg, #2196f3, #1976d2);
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  display: flex;
  align-items: center;
  gap: 8px;
  transition: all 0.3s;
  white-space: nowrap;
}

.add-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(33, 150, 243, 0.3);
}

.notice-list {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.list-header {
  display: grid;
  grid-template-columns: 180px 200px 1fr 120px;
  background: #f8f9fa;
  padding: 15px 20px;
  font-weight: 600;
  color: #666;
  border-bottom: 1px solid #e9ecef;
}

.header-item {
  display: flex;
  align-items: center;
}

.list-content {
  max-height: 600px;
  overflow-y: auto;
}

.list-item {
  display: grid;
  grid-template-columns: 180px 200px 1fr 120px;
  padding: 15px 20px;
  border-bottom: 1px solid #f0f0f0;
  transition: background-color 0.3s;
  align-items: start;
  min-height: auto;
}

.list-item:hover {
  background-color: #f8f9fa;
}

.item-cell {
  display: flex;
  align-items: flex-start;
  padding-right: 10px;
  padding-top: 5px;
}

.time-cell {
  color: #666;
  font-size: 13px;
}

.create-time {
  background: #e3f2fd;
  color: #1976d2;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.title-cell {
  font-weight: 500;
}

.notice-title {
  color: #333;
  font-weight: 600;
  background: #fff3e0;
  color: #f57c00;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 13px;
}

.content-cell {
  color: #666;
  align-items: flex-start;
}

.notice-content {
  word-wrap: break-word;
  word-break: break-all;
  white-space: pre-wrap;
  line-height: 1.5;
  width: 100%;
  padding: 8px 12px;
  background: #f8f9fa;
  border-radius: 6px;
  border-left: 3px solid #2196f3;
  min-height: 20px;
}

.actions {
  justify-content: center;
}

.delete-btn {
  padding: 6px 12px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
  display: flex;
  align-items: center;
  gap: 4px;
  transition: all 0.3s;
  background-color: #ffebee;
  color: #d32f2f;
}

.delete-btn:hover {
  background-color: #d32f2f;
  color: white;
  transform: translateY(-1px);
}

.btn-icon {
  font-size: 14px;
}

.empty-state {
  text-align: center;
  padding: 60px 20px;
  color: #999;
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 16px;
}

.empty-state p {
  font-size: 16px;
  color: #666;
}

/* 弹框样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.edit-section {
  background: white;
  padding: 30px;
  border-radius: 12px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
  width: 400px;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.edit-section input {
  width: 100%;
  padding: 12px 16px;
  border: 2px solid #e1e5e9;
  border-radius: 8px;
  font-size: 14px;
  outline: none;
  transition: border-color 0.3s;
  box-sizing: border-box;
}

.edit-section input:focus {
  border-color: #2196f3;
}

.edit-section button {
  padding: 12px 24px;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.3s;
  margin-right: 10px;
}

.edit-section button:first-of-type {
  background: linear-gradient(135deg, #2196f3, #1976d2);
  color: white;
}

.edit-section button:first-of-type:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(33, 150, 243, 0.3);
}

.edit-section button:last-of-type {
  background-color: #f8f9fa;
  color: #666;
  border: 1px solid #e9ecef;
}

.edit-section button:last-of-type:hover {
  background-color: #e9ecef;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .form-row {
    flex-direction: column;
    align-items: stretch;
  }

  .title-input {
    width: 100%;
  }

  .list-header,
  .list-item {
    grid-template-columns: 1fr;
    gap: 10px;
  }

  .item-cell {
    padding: 5px 0;
    border-bottom: 1px solid #f0f0f0;
  }

  .item-cell:last-child {
    border-bottom: none;
  }

  .edit-section {
    width: 90%;
    max-width: 400px;
  }
}
</style>
